<template>
	<view class="container">
		<view class="payment-form">
			<view class="header">
				<text class="shop-name">{{ shopName }}</text>
			</view>
			<view class="form-item">
				<text class="label">付款金额</text>
				<input type="digit" v-model="amount" class="input" placeholder="请输入付款金额" />
			</view>
			<button @click="handlePayment()" class="payment-button" :disabled="!paymentable">
				立即支付
			</button>
		</view>
	</view>
</template>

<script setup>
	import {
		computed,
		ref
	} from "vue";
	import {
		onLoad,
		onShow
	} from "@dcloudio/uni-app";
	import {
		getShopInfo
	} from "../../api/market";
	import {
		useMainStore
	} from "@/store/store";
	import {
		storeToRefs
	} from "pinia";
	import {
		createScanPaymentOrder
	} from "../../api/order";
	import {
		userAuthSession,
		wechatAuth
	} from '@/api/auth'
	const title = ref("扫码支付");
	const amount = ref("");
	const moneyMaxLeng = ref(8);
	const shop = ref();
	const shopId = ref("");
	const validateAmount = () => {
		let val = amount.value.toString();
		console.log("value:", val);
		val = val.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
		val = val.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
		val = val.replace(/^0+\./g, "0.");
		val = val.match(/^0+[1-9]+/) ? (val = val.replace(/^0+/g, "")) : val;
		val = val.match(/^\d*(\.?\d{0,2})/g)[0] || "";

		if (val.includes(".")) {
			let numDianValue = val.toString().split(".")[1];
			let numDian = numDianValue.length;
			if (numDian === 2) {
				moneyMaxLeng.value = val.length;
			}
			console.log("value:", numDianValue);
			if (numDianValue.length > 2) {
				numDianValue = numDianValue.substring(0, 2);
				amount.value = val.toString().split(".")[0] + numDianValue;
			}
		} else {
			moneyMaxLeng.value = 8;
		}
		amount.value = val;
	};

	const payType = ref("weixin");
	const paymentButtonCustomStyle = computed(() => {
		return {
			width: "80%",
		};
	});
	const paymentable = ref(true);

	const main = useMainStore();
	const {
		member,
		isLogin,
		openid
	} = storeToRefs(main);
	// const onClickLeft = () => {
	// 	uni.navigateBack();
	// }

	const shopName = ref("示例店铺");

	const handlePayment = async () => {
		if (!openid.value) {
			wechatMiniLogin();
		}
		if (!shop.value) {
			console.log("缺少店铺信息");
			// 显示提示消息
			uni.showToast({
				title: "店铺信息不存在",
				icon: "none",
			});
			return;
		}
		// 更具当前输入的金额

		if (amount.value == "" || amount.value == undefined) {
			console.log("请输入正确的金额");
			uni.showToast({
				title: "请输入正确的金额",
				icon: "none",
			});
			return;
		}

		let from = "routine";
		let data = {
			openid: openid.value ?? '',
			orderType: "scan_payment",
			shopId: shop.value.id,
			payType: payType.value,
			form: from,
			amount: amount.value ?? 0,
		};
		// 支付请求中
		uni.showLoading({
			title: "支付请求中",
		});

		paymentable.value = false;
		try {
			let result = await createScanPaymentOrder(data);

			console.log(result);
			if (!result) {
				uni.hideLoading();
				return;
			}

			if (result.trade_type == "MWEB") {
				// #ifdef H5
				// 微信外的H5
				console.log("data:", result);
				location.href = result.data;
				// #endif
				console.log("data1:", result);
			} else if (result.trade_type == "JSAPI") {
				console.log("param:", result);

				// #ifdef MP-WEIXIN
				uni.requestPayment({
					provider: "wxpay",
					timeStamp: result.data.timeStamp,
					nonceStr: result.data.nonceStr,
					package: result.data.package,
					signType: "MD5",
					paySign: result.data.paySign,
					success: function(res) {
						uni.hideLoading();
						paymentable.value = true;
						uni.removeStorageSync("cart");
						uni.switchTab({
							url: "/pages/index/index",
						});
					},
					fail: function(err) {
						console.log("fail:" + JSON.stringify(err));
					},
				});
				// #endif
			}
			// 调用支付接口，支付成功后跳转到支付成功页面
			console.log("支付金额：" + amount.value);
		} catch (error) {
			uni.hideLoading();
			paymentable.value = true;
			console.log(error);
		}
		// this.$router.push("/pages/components/pages/scanpay/pay_success");
	};

	const wechatMiniLogin = () => {
		//this.$u.toast('登录中');
		uni.login({
			provider: 'weixin'
		}).then(async (res) => {
			let data = await userAuthSession({
				code: res.code
			});
			if (data) {
				main.SET_OPENID(data.openId)
				console.log('openid', data.openId);

				if (data.hasOwnProperty('userInfo') && data.accessToken && data.accessToken != '') {
					main.SET_MEMBER(data.userInfo);
					main.SET_TOKEN(data.accessToken);
					main.SET_ACCESSES(data.accesses);
				}
			}
		});
	}

	onShow(() => {
		console.log("init");

		if (!openid.value) {
			wechatMiniLogin();
		}

		if (shopId.value) {
			console.log("shopId =>>", shopId.value);
			loadShopInfo(shopId.value).then((result) => {
				console.log(result);
			});
		}
		paymentable.value = true;
		console.log(paymentable.value);


	});



	onLoad((options) => {
		//没从当前url 获取 参数 shopId 的值
		// 通过uni.getStorageSync('shopId') 获取

		console.log("options=>>>>", options);

		// 扫码截取参数
		if (options.q !== undefined) {
			let q = decodeURIComponent(options.q);
			// q 是解码后的完整url
			console.log("q", q); // 打印出完整的二维码内容

			// 如果需要获取特定的参数，可以使用正则表达式或者分割字符串的方法
			// 例如，获取名为 'combo_code' 的参数
			let comboCodeParams = q.split("shopId=")[1].split("&")[0];
			console.log(comboCodeParams); // 打印出 'combo_code' 参数的值
			shopId.value = comboCodeParams;
		}

		paymentable.value = true;
		console.log(paymentable.value);
	});

	const loadShopInfo = async (shopId) => {
		// 后台检查 shopId 是否存在
		const shopInfo = await getShopInfo({
			shopId: shopId,
		});
		if (shopInfo) {
			console.log(shopInfo);
		} else {
			console.log("load shop info fail");
		}
		if (shopInfo) {
			shop.value = shopInfo;
			title.value = shopInfo.name;
			shopName.value = shopInfo.name ?? "示例店铺";
		} else {
			console.log("店铺信息不存在");
			shop.value = null;
		}

		return "success";
	};
</script>

<style>
	.container {
		padding: 20px;
	}

	.payment-form {
		margin-top: 50px;
		background-color: #ffffff;
		border-radius: 10px;
		padding: 20px;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
	}

	.header {
		/* background-color: #07c160; */
		padding: 20px;
		text-align: center;
	}

	.form-item {
		margin-bottom: 20px;
	}

	.label {
		display: block;
		margin-bottom: 5px;
		font-size: 14px;
		color: #333;
	}

	.input {
		width: 100%;
		height: 50px;
		border: 1px solid #dcdfe6;
		border-radius: 4px;
		padding: 0 15px;
		font-size: 14px;
	}

	.payment-button {
		width: 100%;
		height: 40px;
		background-color: #007aff;
		color: #ffffff;
		border: none;
		border-radius: 4px;
		font-size: 16px;
	}
</style>